package com.rjwh.dingdong.client.activity.player.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aishua.lib.utils.AsStrUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.bean.localbean.Song;
import com.rjwh.dingdong.client.fragment.BaseFragment;
import com.rjwh.dingdong.client.mvp.presenter.impl.PlayerToolbarPresenter;
import com.rjwh.dingdong.client.mvp.view.PlayerToolbarView;
import com.rjwh.dingdong.client.player.IPlayback;
import com.rjwh.dingdong.client.player.PlayConstants;
import com.rjwh.dingdong.client.player.PlayMode;
import com.rjwh.dingdong.client.player.PlayState;
import com.rjwh.dingdong.client.service.PlaybackService;
import com.rjwh.dingdong.client.util.RxBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * 项目名称：whrjwh-parent
 * 类描述：全局使用的播放控制的工具栏
 * 创建人：wby
 * 创建时间：2016/10/26 9:22
 * 修改人：wby
 * 修改时间：2016/10/26 9:22
 * 修改备注：
 *
 * @version V1.0
 */
public class PlayerToolbarFragment extends BaseFragment implements PlayerToolbarView {


    @BindView(R.id.playbar_img)
    ImageView playbarImg;
    @BindView(R.id.tv_music_title)
    TextView tvMusicTitle;
    @BindView(R.id.player_music_duration_tv)
    TextView playerMusicDurationTv;
    @BindView(R.id.play_list)
    ImageView playList;
    @BindView(R.id.player_play_or_pause_btn)
    ImageView playerPlayOrPauseBtn;
    @BindView(R.id.linear)
    LinearLayout linear;
    @BindView(R.id.player_music_progress_sb)
    ProgressBar playerMusicProgressSb;

    private IPlayback mPlayer;
    private PlayerToolbarPresenter presenter;

    private Observable<Song> observableUpdateSong;
    private Observable<Integer> observablePlayChange;
    private Observable<PlayState> observablePlayState;
    private Observable<Integer> observablePlaySeuess;
    /**
     * 是否正在拖进度条
     */
    private boolean isTrackingTouch;

    public static PlayerToolbarFragment getInstance() {
        PlayerToolbarFragment fragment = new PlayerToolbarFragment();
        Bundle bd = new Bundle();
        fragment.setArguments(bd);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.player_toolbar_nav, container, false);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        presenter = new PlayerToolbarPresenter(getContext(), this);
        presenter.subscribe();
        init();
    }

    public void init() {
//        playerMusicProgressSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                if (fromUser) {
//                    updateProgressTextWithProgress(progress);
//                }
//            }
//
//            @Override
//            public void onStartTrackingTouch(SeekBar seekBar) {
//                // 标识：开始拖进度
//                isTrackingTouch = true;
//            }
//
//            @Override
//            public void onStopTrackingTouch(SeekBar seekBar) {
//                // 标识：已停止拖进度
//                isTrackingTouch = false;
//                presenter.seek(playerMusicProgressSb.getProgress());
//            }
//        });
        observableUpdateSong = RxBus.get().register(PlayConstants.ACTION_UPDATA_SONG, Song.class);
        observablePlayChange = RxBus.get().register(PlayConstants.ACTION_PLAY_PROG, Integer.class);
        observablePlayState = RxBus.get().register(PlayConstants.ACTION_PLAY_STATUS_CHANGED, PlayState.class);
        observablePlaySeuess = RxBus.get().register(PlayConstants.ACTION_PLAY_SECOND_PROG, Integer.class);
        addSubscription(observableUpdateSong, subscriberUpdateSong);
        addSubscription(observablePlayChange, subscriberPlayChange);
        addSubscription(observablePlayState, subscriberPlayState);
//        addSubscription(observablePlaySeuess, subscriberPlaySeuess);
    }


    @Override
    public void onPlaybackServiceBound(PlaybackService service) {
        this.mPlayer = service;
    }

    @Override
    public void onPlaybackServiceUnbound() {
        mPlayer = null;
    }

    @Override
    public void onSongUpdated(@Nullable Song song) {
        resetRefreshView();
        if (song == null) {
            return;
        }
        if (!AsStrUtils.isEmpty(song.getProgramname())) {
            tvMusicTitle.setText(song.getProgramname());
        }
        Glide.with(this).load(song.getCoverurl()).dontAnimate()
                .placeholder(R.drawable.icon_radio_player_cover_holder).error(R.drawable.icon_radio_player_cover_holder)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(playbarImg);
        if (mPlayer != null) {
            if (mPlayer.getPlayStatus() == PlayState.PLAY || mPlayer.getPlayStatus() == PlayState.PAUSE) {
                updateProgressTextWithDuration(mPlayer.getDuration());
                updateProgressTextWithProgress(mPlayer.getProgress());
            }
            updatePlayToggle(mPlayer.getPlayStatus());
        }
    }

    @Override
    public void updatePlayMode(PlayMode playMode) {
        //暂未实现
    }

    //重置界面UI状态
    private void resetRefreshView() {
        tvMusicTitle.setText("请选择节目播放");
        playerMusicProgressSb.setMax(0);
        playerMusicProgressSb.setProgress(0);
//        playerMusicProgressSb.setSecondaryProgress(0);
//        playerMusicCurrentPositionTv.setText(convertTime(0));
        playerMusicDurationTv.setText(convertTime(0));
        playerPlayOrPauseBtn.setImageResource(R.drawable.playbar_btn_play);
    }

    @Override
    public void updatePlayToggle(PlayState change) {
        playerPlayOrPauseBtn.setEnabled(true);
        //缓冲中
        if (change == PlayState.READY) {
            playerPlayOrPauseBtn.setEnabled(false);
            playerPlayOrPauseBtn.setImageResource(R.drawable.playbar_btn_pause);
        }
        //播放中
        else if (change == PlayState.PLAY) {
            playerPlayOrPauseBtn.setImageResource(R.drawable.playbar_btn_pause);
        }
        //暂停
        else if (change == PlayState.PAUSE) {
            playerPlayOrPauseBtn.setImageResource(R.drawable.playbar_btn_play);
        }
        //暂停
        else if (change == PlayState.STOP) {
            playerPlayOrPauseBtn.setImageResource(R.drawable.playbar_btn_play);
        }
    }

    //刷新进度条控制
    private void updateProgressTextWithProgress(int progress) {
        // 判断用户是否正在拖进度条，如果在拖，则不更新SeekBar
//        if (!isTrackingTouch) {
//            playerMusicCurrentPositionTv.setText(convertTime(progress));
        //设置当前播放到的时长
        playerMusicDurationTv.setText(convertTime(progress));
        playerMusicProgressSb.setProgress(progress);
//        }
    }

    //更新总时间
    private void updateProgressTextWithDuration(int duration) {
//        playerMusicDurationTv.setText(convertTime(duration));
        playerMusicProgressSb.setMax(duration);
    }

    //刷新缓冲进度条
    private void updateSecondaryProgress(int duration) {
//		double prog = (duration/100)*sbMusicProgress.getMax();
        float num = ((float) duration / 100) * playerMusicProgressSb.getMax();
        playerMusicProgressSb.setSecondaryProgress((int) num);
    }

    /**
     * convert time str
     *
     * @param time
     * @return
     */
    public String convertTime(int time) {

        time /= 1000;
        int minute = time / 60;
        int second = time % 60;
        minute %= 60;
        return String.format("%02d:%02d", minute, second);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(PlayConstants.ACTION_UPDATA_SONG, observableUpdateSong);
        RxBus.get().unregister(PlayConstants.ACTION_PLAY_PROG, observablePlayChange);
        RxBus.get().unregister(PlayConstants.ACTION_PLAY_STATUS_CHANGED, observablePlayState);
        RxBus.get().unregister(PlayConstants.ACTION_PLAY_SECOND_PROG, observablePlaySeuess);
        presenter.detachView();
    }

    @OnClick({R.id.player_play_or_pause_btn, R.id.play_list, R.id.player_next_btn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.player_play_or_pause_btn:
                presenter.startPlayMusic();
                break;
            case R.id.play_list:
                presenter.playPrevMusic();
                break;
            case R.id.player_next_btn:
                presenter.playNextMusic();
                break;
        }
    }

    Subscriber subscriberUpdateSong = new Subscriber<Song>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(Song song) {
            onSongUpdated(song);
        }
    };
    Subscriber subscriberPlayChange = new Subscriber<Integer>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(Integer change) {
            updateProgressTextWithDuration(mPlayer.getDuration());
            updateProgressTextWithProgress(change);
        }
    };
    Subscriber subscriberPlayState = new Subscriber<PlayState>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(PlayState change) {
            updatePlayToggle(change);
            if (change == PlayState.PLAY) {
                updateProgressTextWithDuration(mPlayer.getDuration());
            }
        }
    };
//    Subscriber subscriberPlaySeuess = new Subscriber<Integer>() {
//        @Override
//        public void onCompleted() {
//
//        }
//
//        @Override
//        public void onError(Throwable e) {
//
//        }
//
//
//        @Override
//        public void onNext(Integer prog) {
//            updateSecondaryProgress(prog);
//        }
//    };

}
